package com.xmb.wcapi.util;

import java.util.HashMap;
import java.util.Map;

import javax.servlet.ServletOutputStream;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;

import org.springframework.stereotype.Controller;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.servlet.ModelAndView;

import com.google.zxing.BarcodeFormat;
import com.google.zxing.EncodeHintType;
import com.google.zxing.MultiFormatWriter;
import com.google.zxing.WriterException;
import com.google.zxing.client.j2se.MatrixToImageWriter;
import com.google.zxing.common.BitMatrix;
import com.google.zxing.qrcode.QRCodeWriter;

@Controller
@RequestMapping("/graphics")
public class QRCodeUtil {
    /**
     * 生成二维码方法
     *
     * @param  content 要生成的内容
     * @param resp response对象
     * @throws Exception 抛出异常
     */
	@RequestMapping("/generateQrcode")
    public void generateQrcode(String content, HttpServletRequest req, HttpServletResponse resp) throws Exception {
    	ServletOutputStream stream = null;
    	try {
    		stream = resp.getOutputStream();
    		Map<EncodeHintType, Object> hints = new HashMap<>();
    		//编码
    		hints.put(EncodeHintType.CHARACTER_SET, "utf-8");
    		//边框距
    		hints.put(EncodeHintType.MARGIN, 0);
    		QRCodeWriter qrCodeWriter = new QRCodeWriter();
    		BitMatrix bm = qrCodeWriter.encode(content, BarcodeFormat.QR_CODE, 150, 150, hints);
    		MatrixToImageWriter.writeToStream(bm, "png", stream);
    	} catch (WriterException e) {
    		e.getStackTrace();
	
    	} finally {
    		if (stream != null) {
    			stream.flush();
    			stream.close();
    		}
    	}
    }
    
    /**
     * 条形码编码
     * 
     * @param contents
     * @param width
     * @param height
     * @param imgPath
     */
	@RequestMapping("/generateBarCode")
    public void generateBarCode(String content, HttpServletRequest req, HttpServletResponse resp) throws Exception {
		resp.setHeader("Access-Control-Allow-Credentials", "true");
    	ServletOutputStream stream = null;
		try {
			stream = resp.getOutputStream();
			int codeWidth = 3 + // start guard
					(7 * 6) + // left bars
					5 + // middle guard
					(7 * 6) + // right bars
					3; // end guard
			codeWidth = Math.max(codeWidth, 105);
			BitMatrix bitMatrix = new MultiFormatWriter().encode(content,BarcodeFormat.CODE_128, codeWidth, 50, null);
			MatrixToImageWriter.writeToStream(bitMatrix, "png", stream);
		} catch (Exception e) {
			e.printStackTrace();
		}finally {
    		if (stream != null) {
    			stream.flush();
    			stream.close();
    		}
    	}
    }
    
    //打开生成二维码页面。
    @RequestMapping(value = "/open1")
    public ModelAndView open1(String qrid1){
        ModelAndView mv = new ModelAndView();
        qrid1="当前票为空"; 
        mv.addObject("qrid",qrid1);
        mv.setViewName("/qrcode.btl");
        return mv;
    }
}
